# coding=utf-8
from django.shortcuts import render
from . import models
from django.http import JsonResponse, HttpResponse

import json
import os
import time

from rest_framework.views import APIView
from rest_framework import exceptions
from rest_framework import serializers
# from rest_framework.pagination import CursorPagination

# 用户认证
from User.utils.auth import TokenAuth
from User.utils.permission import CadrePermission

ret = {'code': '', 'msg': '', 'data':''}
def getToken(request):
     return request.META.get("HTTP_TOKEN")

def getUser(request):
    try:
        token = getToken(request)
        Obj = models.User_Token.objects.filter(
                    token=token).first()
        return Obj.user
    except:
        return


def md5(user):
    import hashlib
    import time
    ctime = str(time.time())
    m = hashlib.md5(bytes(user, encoding='utf-8'))
    m.update(bytes(ctime, encoding='utf-8'))
    return m.hexdigest()

def updateToken(User_AccountObj, token):
    TokenObj = models.User_Token.objects.filter(user=User_AccountObj).first()
    if not TokenObj:
        models.User_Token.objects.create(user=User_AccountObj, token=token)
    else:
        models.User_Token.objects.filter(
            user=User_AccountObj).update(token=token)

class login(APIView):
    """
        post:
            # 
            Title: 登录
            Request: username-password
            Return: name-token
            Permissions: /
    """
    def post(self, request, *args, **kwargs):
        ret = {'code': '', 'msg': '', 'data':''}
        try:
            user = request.data['username']  # .POST.get('phone')
            pwd = request.data['password']  # POST.get('password')
        except Exception as e:
            print("前端数据异常")
            ret['code'] = 5000
        try:
            Obj = models.User.objects.filter(
                username=user, password=pwd).first()
            if not Obj:
                ret['code'] = 3000
                ret['msg'] = '密码错误'
                return JsonResponse(ret)
            # 创建token
            token = md5(user)
            updateToken(Obj, token)
            ret['code'] = 2000
            ret['data'] = {"token":token,"name":Obj.name}
        except Exception as e:
            ret['code'] = 5000

        return JsonResponse(ret)



class information(APIView):
    def get(self,request):
        ret={"code":000,"data":{"name":"null"}}     
        ret["data"]["name"]=getUser(request).name                                                    
        ret["code"] = 200                                                                                   
        return JsonResponse(ret)